<template>
  <div class="app-container">
    <a-card class="info-card">
      <strong class="title text-lg">企业信息</strong>
      <div class="info-container">
        <p>企业简称：{{ data?.companyAbbrName }}</p>
        <p>商户号：{{ userId }}</p>
        <p>联系人：{{ data?.name }}</p>
        <p>联系方式：{{ data?.phone }}</p>
        <p>地址：{{ data?.addr }}</p>
      </div>
    </a-card>
    <a-card class="info-card text-lg">
      <strong class="title">通道产品</strong>
      <div class="info-container">
        <div class="container-box border-box" v-if="interlinked && interlinked.length > 0">
          <div class="container-box-title">间连业务</div>
          <div class="container-box-content">
            <div class="container-box-item" v-for="(item, index) in interlinked" :key="index">
              <a-row justify="space-around" align="middle">
                <a-col :span="3">{{ item.channelName }}</a-col>
                <a-col :span="3">
                  <a-button
                    type="link"
                    size="small"
                    @click="viewData(item)"
                    :disabled="item.auditStatus == ZZB_MCH_AUDIT_STATUS_ENUM.MCH_AUDIT_NO_SUBMITTED.desc"
                    >查看资料
                  </a-button>
                </a-col>
                <a-col :span="3">{{ item.auditStatus }}</a-col>
                <a-col :span="3">{{ item.auditDetail }}</a-col>
                <a-col :span="2"> <a-button type="link" size="small" @click="copy(item.signUrl)" v-if="item.signUrl">签约复制 </a-button></a-col>
                <!-- <a-col :span="3">
                  <a-button
                    type="link"
                    size="small"
                    :disabled="
                      !(item.payMethod.some((item) => item.isOpen) && item.auditStatus === ZZB_MCH_AUDIT_STATUS_ENUM.MCH_AUDIT_FINISHED.desc)
                    "
                    @click="configParam()"
                    >支付参数配置
                  </a-button>
                </a-col> -->
                <a-col :span="2">
                  <a-button type="link" size="small" @click="setRate(item)" :disabled="setRateDisabled(item)">设置费率 </a-button>
                </a-col>
                <a-col :span="6" style="text-align: right">
                  <div style="line-height: 2em" v-for="(item1, index) in item.payMethod" :key="`${item1.name}${index}`">
                    <span style="vertical-align: middle; padding-right: 8px">{{ getFlagDescType(item1.name) }}</span>
                    <a-switch v-model:checked="item1.isOpen" disabled />
                  </div>
                </a-col>
              </a-row>
            </div>
            <div class="container-box-item">
              <div>说明：T+1到账，同一收款方式，间连业务仅能开通一个。</div>
            </div>
          </div>
        </div>
        <div class="container-box border-box m-t-20px">
          <div class="container-box-title">直连业务</div>
          <div class="container-box-content">
            <div class="container-box-item" v-for="(item, index) in direct" :key="index">
              <a-row justify="space-around" align="middle">
                <a-col :span="3">{{ item.channelName }}</a-col>
                <a-col :span="3">
                  <a-button
                    type="link"
                    size="small"
                    @click="viewData(item)"
                    :disabled="item.auditStatus == ZZB_MCH_AUDIT_STATUS_ENUM.MCH_AUDIT_NO_SUBMITTED.desc"
                    >查看资料
                  </a-button>
                </a-col>
                <a-col :span="3">{{ item.auditStatus }}</a-col>
                <a-col :span="3">{{ item.auditDetail }}</a-col>
                <a-col :span="2"> <a-button type="link" size="small" @click="copy(item.signUrl)" v-if="item.signUrl">签约复制 </a-button></a-col>
                <!-- <a-col :span="3">
                  <a-button
                    type="link"
                    size="small"
                    :disabled="
                      !(item.payMethod.some((item) => item.isOpen) && item.auditStatus === ZZB_MCH_AUDIT_STATUS_ENUM.MCH_AUDIT_FINISHED.desc)
                    "
                    @click="configParam()"
                    >支付参数配置
                  </a-button>
                </a-col> -->
                <a-col :span="2">
                  <a-button type="link" size="small" @click="setRate(item)" :disabled="setRateDisabled(item)">设置费率 </a-button>
                </a-col>

                <a-col :span="6" style="text-align: right">
                  <div style="line-height: 2em" v-for="(item1, index) in item.payMethod" :key="`${item1.name}${index}`">
                    <span style="vertical-align: middle; padding-right: 8px">{{ getFlagDescType(item1.name) }}</span>
                    <a-switch v-model:checked="item1.isOpen" disabled />
                  </div>
                </a-col>
              </a-row>
            </div>
            <div class="container-box-item">
              <div>说明：走官方接口，微信支付可关注公众号。</div>
            </div>
          </div>
        </div>
      </div>
    </a-card>
    <a-modal v-model:open="open" title="更新秘钥" @ok="handleOk" @cancel="handleCancel">
      <a-form ref="formRef" :model="formSecret" name="basic" autocomplete="off" layout="vertical" :rules="rules">
        <a-form-item label="管理员账号" name="username">
          <a-input v-model:value="formSecret.username" />
        </a-form-item>

        <a-form-item label="管理员密码" name="password">
          <a-input-password v-model:value="formSecret.password" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="openRate" title="设置费率" @ok="handleRateOk" @cancel="handleRateCancel">
      <a-form ref="formRateRef" :model="formRate" name="basic" autocomplete="off" layout="vertical" :rules="rulesRate">
        <a-form-item label="线上费率" name="onlineRate">
          <a-input-number v-model:value="formRate.onlineRate" :min="0" :max="100" :step="0.01" style="width: 100%" placeholder="线上费率" />
        </a-form-item>
        <a-form-item label="线下费率" name="offlineRate">
          <a-input-number v-model:value="formRate.offlineRate" :min="0" :max="100" :step="0.01" style="width: 100%" placeholder="线下费率" />
        </a-form-item>
      </a-form>
    </a-modal>

    <alipayForm v-model:open="openAlipay" :formType="formType" :formData="initFormData" :params="infoParams" ref="alipayRef" @ok="handleFormOk" />
    <weChatForm v-model:open="openWechat" :formType="formType" :formData="initFormData" :params="infoParams" ref="weChatRef" @ok="handleFormOk" />
    <yeepayForm v-model:open="openYeepay" :formType="formType" :formData="initFormData" :params="infoParams" ref="yeepayRef" @ok="handleFormOk" />
    <lakalaForm v-model:open="openLakala" :formType="formType" :formData="initFormData" :params="infoParams" ref="lakalaRef" @ok="handleFormOk" />
  </div>
</template>
<script setup name="Channel">
  import alipayForm from '/@/components/business/comment/registForm/alipayForm.vue'
  import weChatForm from '/@/components/business/comment/registForm/weChatForm.vue'
  import yeepayForm from '/@/components/business/comment/registForm/yeepayForm.vue'
  import lakalaForm from '/@/components/business/comment/registForm/lakalaForm.vue'
  import { getCurrentInstance, nextTick, reactive, ref, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { agentChannelApi } from '/@/api/business/b-agent/agent/agent-channel-api.js'
  import { ZZB_CHANNEL_TYPE_ENUM } from '/@/constants/business/b-operation/channel/channels-const.js'
  import { ZZB_MCH_AUDIT_STATUS_ENUM } from '/@/constants/business/b-operation/expand/business-application-const.js'
  import { mchRegistApi } from '/@/api/business/b-agent/regist/mch-regist-api.js'
  import { message } from 'ant-design-vue'
  import { useUserStore } from '/@/store/modules/system/user.js'
  import { selectDictLabel } from '/@/utils/common.js'
  import {
    CHANNEL_BUSINESS_TYPE, // 通道业务类型
  } from '/@/constants/dict'
  const { proxy } = getCurrentInstance()

  const state = useUserStore()

  const route = useRoute()
  // const userType = parseInt(localRead(LocalStorageKeyConst.USER_TYPE))
  const userId = ref('')

  const data = ref()
  watch(
    [() => route.query.merchantData],
    async () => {
      if (route.query.merchantData) {
        let mercdata = JSON.parse(route.query.merchantData)
        userId.value = mercdata.id
        data.value = mercdata
        getList()
      }
    },
    {
      immediate: true,
    },
  )

  // 间连数据
  const interlinked = ref([])
  // 直连数据
  const direct = ref([]) // 初始化为空数组，由init函数填充

  const findExpandInfo = async (val) => {
    const param = {
      merchantId: userId.value,
      channelId: val.channelId,
    }
    const res = await mchRegistApi.findOne(param)

    if (val.channelId === res.data?.channelId) {
      expandInfo.data = res.data
    }
  }

  const expandInfo = reactive({
    data: undefined,
  })

  // 初始化数据
  const initFormData = ref({})

  // 资料录入表单弹窗
  const infoParams = reactive({
    channelId: undefined,
    merchantId: undefined,
    businessType: undefined,
  })

  const openAlipay = ref(false)
  const openWechat = ref(false)
  const openYeepay = ref(false)
  const openLakala = ref(false)
  const formType = ref('add')

  const initForm = (val, type) => {
    formType.value = type
    openAlipay.value = val.channelType === ZZB_CHANNEL_TYPE_ENUM.CHANNEL_TYPE_ALIPAY.value
    openWechat.value = val.channelType === ZZB_CHANNEL_TYPE_ENUM.CHANNEL_TYPE_WECHATPAY.value
    openYeepay.value = val.channelType === ZZB_CHANNEL_TYPE_ENUM.CHANNEL_TYPE_YEEPAY.value
    openLakala.value = val.channelType === ZZB_CHANNEL_TYPE_ENUM.CHANNEL_TYPE_LKLPAY.value
    infoParams.channelId = val.channelId
    infoParams.merchantId = userId.value
    infoParams.businessType = val.businessType
    infoParams.channelType = val.channelType
  }

  // 查看资料
  const viewData = async (val) => {
    await findExpandInfo(val)
    await nextTick()
    const param = { ...expandInfo.data }

    initForm(val, 'view')

    initFormData.value = param
  }

  // 支付参数配置
  const configParam = () => {}

  // 秘钥模块
  const open = ref(false)
  const formSecret = reactive({
    username: undefined,
    password: undefined,
  })
  const rules = ref({
    username: [{ required: true, message: '管理员账号不能为空!' }],
    password: [{ required: true, message: '管理员密码不能为空!' }],
  })
  const formRef = ref()
  const openModal = () => {
    open.value = true
  }
  const handleOk = () => {
    // open.value = false
    formRef.value
      .validate()
      .then(() => {})
      .catch(() => {})
  }
  const handleCancel = () => {
    resetForm()
    // open.value = false
  }
  const resetForm = () => {
    formRef.value.resetFields()
  }
  // 枚举映射函数
  const getFlagDescStatus = (value) => {
    const enumValues = Object.values(ZZB_MCH_AUDIT_STATUS_ENUM)
    const matchedEnum = enumValues.find((enumItem) => enumItem.value === value)
    return matchedEnum ? matchedEnum.desc : '未知状态'
  }
  const getFlagDescType = (value) => {
    return selectDictLabel(CHANNEL_BUSINESS_TYPE, value)
  }
  //业务数据初始化列表
  async function getList() {
    const param = {
      merchantId: userId.value,
      agentId: state.userId,
      statusFlag: true,
      pageNo: 1,
      pageSize: 10,
    }
    try {
      // console.log('列表请求参数==>', param)
      const res = await agentChannelApi.pageMch(param)
      // console.log('列表数据==>', res.data)
      direct.value = []
      interlinked.value = []
      if (res.code === 200 && res.data) {
        res.data.forEach((item) => {
          if (item.directFlag) {
            // 直连数据
            direct.value.push({
              ...item,
              auditStatus: getFlagDescStatus(item.auditStatus),
              payMethod: [
                {
                  name: item.businessType,
                  isOpen: item.channelStatus === 1,
                },
              ],
            })
          } else {
            // 间连数据
            interlinked.value.push({
              ...item,
              auditStatus: getFlagDescStatus(item.auditStatus),
              payMethod: [
                {
                  name: item.businessType,
                  isOpen: item.channelStatus === 1,
                },
              ],
            })
          }
        })
        console.log('直连===>', direct.value)
        console.log('间连===>', interlinked.value)
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 设置费率禁用状态
  const setRateDisabled = (row) => {
    return row.auditStatus == '已提交' || row.auditStatus == '审核中' || row.auditStatus == '已完成'
  }

  /* 设置费率开始 */
  const openRate = ref(false)
  const formRateRef = ref()
  const formRate = ref({})
  const rulesRate = ref({
    onlineRate: [{ required: true, message: '线上费率不能为空!' }],
    offlineRate: [{ required: true, message: '线下费率不能为空!' }],
  })
  const setRate = (row) => {
    formRate.value = {
      merchantId: userId.value,
      channelId: row.channelId,
      onlineRate: row?.onlineRate,
      offlineRate: row?.offlineRate,
    }
    openRate.value = true
  }
  const handleRateOk = () => {
    formRateRef.value
      .validate()
      .then(() => {
        mchRegistApi.updateRate(formRate.value).then((res) => {
          if (res.code === 200) {
            message.success('设置成功')
            openRate.value = false
            getList()
          }
        })
      })
      .catch(() => {})
  }
  const handleRateCancel = () => {
    openRate.value = false
  }
  /* 设置费率结束 */

  // 提交后刷新数据
  const handleFormOk = () => {
    getList()
  }

  // ----------------- 复制操作 -----------------
  function copy(content) {
    // 创建元素用于复制
    const aux = document.createElement('input')
    // 设置元素内容
    aux.setAttribute('value', content)
    // 将元素插入页面进行调用
    document.body.appendChild(aux)
    // 复制内容
    aux.select()
    // 将内容复制到剪贴板
    document.execCommand('copy')
    // 删除创建元素
    document.body.removeChild(aux)

    message.success('复制成功')
  }
  // onMounted(() => {
  //   getList()
  //   // perInfo()
  // })
</script>
<style scoped lang="less">
  .info-card {
    &:nth-child(1) {
      margin-top: 10px;
    }

    margin-bottom: 20px;
  }

  .info-container {
    padding-top: 20px;
    margin: 0 20px;

    p {
      margin-bottom: 0.5em;
    }

    .container-box {
      .container-box-title {
        padding: 10px 20px;
        border-bottom: 1px solid #e8e8e8;
      }

      .container-box-content {
        padding: 10px 20px;

        .container-box-item {
          padding: 10px;
          border-bottom: 1px solid #e8e8e8;

          &:last-of-type {
            border: none;
          }
        }
      }
    }
  }

  .border-box {
    border: 1px solid #e8e8e8;
  }

  .update-btn {
    margin-left: 20px;
    background-color: rgba(245, 154, 35, 1);

    &:hover {
      background-color: rgba(245, 154, 35, 0.6);
    }
  }
</style>
